package com.loong.musicdemo.ui.find.activity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.palette.graphics.Palette;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.appbar.AppBarLayout;
import com.loong.musicdemo.PlaySongActivity;
import com.loong.musicdemo.R;
import com.loong.musicdemo.model.Song;
import com.loong.musicdemo.service.AutoPlayService;
import com.loong.musicdemo.service.DownloadService;
import com.loong.musicdemo.ui.find.adapter.AlbumSongAdapter;
import com.loong.musicdemo.util.BlurUtil;
import com.loong.musicdemo.util.FormatTimeUtil;
import com.loong.musicdemo.util.dataDeal.MusicDeal;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class ShowAlbumPlayListActivity extends AppCompatActivity {
    private ImageView album_image;
    CircleImageView album_creatorImg;
    private TextView album_name, album_play_count, album_creatorName, album_commentCount;
    private Intent songIntent;
    private static List<String> songIds = new ArrayList<>();
    private RecyclerView album_playlist;
    private SmartRefreshLayout loading;//上拉加载控件
    private List<Song> songsList = new ArrayList<>();
    private AlbumSongAdapter listAdapter;
    private ProgressBar progressBar;
    private CoordinatorLayout bcgImg;//背景图片
    private LinearLayout comment_layout;
    private RelativeLayout listInfo;//歌单信息


    //下载服务
    private DownloadService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            downloadBinder = (DownloadService.DownloadBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //背景图片融合
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        setContentView(R.layout.activity_show_play_list);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);//若工具栏可用,则显示Home菜单
        }
        initView();
        getSongIntent();
        initRecyclerView();
        //前往评论页面
        comment_layout.setOnClickListener(v -> {
            Intent intent = new Intent(ShowAlbumPlayListActivity.this, CommentListActivity.class);
            intent.putExtra("id", songIntent.getStringExtra("albumId"));
            startActivity(intent);
        });
        //加载背景模糊图片
        Glide.with(this).asBitmap()
                .load(songIntent.getStringExtra("albumImg"))
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        Bitmap bitmap = BlurUtil.doBlur(resource, 10, 10);
                        Palette palette = Palette.from(bitmap).generate();
                        Palette.Swatch swatch = palette.getVibrantSwatch();
                        if (swatch == null) {//无鲜明色调--颜色过于单调,则防止亮度过高,使用默认图片
                            swatch = palette.getDominantSwatch();//主色调
                            if (swatch != null && !(swatch.getHsl()[2] > 0.85)) {//正常亮度
                                bcgImg.setBackground(new BitmapDrawable(bitmap));
                            } else {//纯色背景修改
                                bcgImg.setBackgroundResource(R.drawable.bcg_account_fragment);
                            }
                        } else {
                            bcgImg.setBackground(new BitmapDrawable(bitmap));
                        }
                    }
                });

        new Thread(() -> {
            List<Song> songs;
            if (songIds.size() <= 20) {
                songs = MusicDeal.getSongListByIds(songIds);
                songIds.clear();
            } else {
                List<String> list = songIds.subList(0, 20);
                songIds = songIds.subList(20, songIds.size());
                songs = MusicDeal.getSongListByIds(list);
            }
            songsList.addAll(songs);
            runOnUiThread(() -> {
                progressBar.setVisibility(View.GONE);
                listAdapter.notifyDataSetChanged();
            });
        }).start();//初始化前20条数据


        //启动下载服务
        Intent intent = new Intent(this, DownloadService.class);
        startService(intent);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        album_playlist.setLayoutManager(layoutManager);
        listAdapter = new AlbumSongAdapter(songsList);
        album_playlist.setAdapter(listAdapter);
        //添加歌曲旁按钮播放事件
        listAdapter.setClickListener(new AlbumSongAdapter.OnClickPlayButton() {
            @Override
            public void onPlayNowClick(int position) {
                //直接进行播放
                Song song = songsList.get(position);
                String playUrl = song.getPlayUrl();
                if (playUrl.equals("null") || playUrl.equals("")) {
                    //播放地址不存在
                    Toast.makeText(ShowAlbumPlayListActivity.this, "非常抱歉，歌曲无法播放！", Toast.LENGTH_SHORT).show();
                } else {
                    //立即播放
                    Intent intent = new Intent(ShowAlbumPlayListActivity.this, PlaySongActivity.class);
                    intent.putExtra("songId", song.getSongId());
                    startActivity(intent);
                }
            }

            @Override
            public void onAddToList(int position) {
                //添加到播放列表
                Song song = songsList.get(position);
                String playUrl = song.getPlayUrl();
                if (playUrl.equals("null") || playUrl.equals("")) {
                    //播放地址不存在
                    Toast.makeText(ShowAlbumPlayListActivity.this, "非常抱歉，歌曲无法播放！", Toast.LENGTH_SHORT).show();
                } else {
                    //添加到播放列表
                    Message msg = AutoPlayService.handler.obtainMessage();//创建消息对象
                    //讲传来的音乐id封装至消息对象中
                    Bundle bundle = new Bundle();
                    bundle.putString("songId", song.getSongId());
                    msg.setData(bundle);
                    AutoPlayService.handler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 设置返回菜单
     *
     * @param item 菜单项
     * @return 是否触发
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home)
            this.finish();
        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取从别的活动传来的专辑数据以及专辑中的歌曲id
     */
    @SuppressLint("CheckResult")
    private void getSongIntent() {
        songIntent = getIntent();
        //初始化Glide圆角配置
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.circleCropTransform();
        requestOptions.bitmapTransform(new RoundedCorners(10));
        requestOptions.placeholder(R.drawable.temp);
        Glide.with(this).load(songIntent.getStringExtra("albumImg")).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).into(album_image);
        Glide.with(this).load(songIntent.getStringExtra("albumCreatorPic")).diskCacheStrategy(DiskCacheStrategy.NONE).apply(requestOptions).skipMemoryCache(true).into(album_creatorImg);
        album_name.setText(songIntent.getStringExtra("albumName"));
        album_play_count.setText(FormatTimeUtil.briefNumber(songIntent.getStringExtra("albumPlayCount")));
        album_creatorName.setText(songIntent.getStringExtra("albumCreatorName"));
        String albumCommentCount = songIntent.getStringExtra("albumCommentCount");
        if (albumCommentCount == null || albumCommentCount.equals("")) {
            albumCommentCount = "0";
        }
        album_commentCount.setText(FormatTimeUtil.briefNumber(albumCommentCount));
        songIds = songIntent.getStringArrayListExtra("albumIDs");
    }

    /**
     * 初始化所有的控件
     */
    private void initView() {
        //下载全部
        LinearLayout download_all = findViewById(R.id.download_all);
//        download_all.setOnClickListener(v -> new Thread(() -> SongDownload.downloadSongs(songsList)).start());//开始下载
        download_all.setOnClickListener(view -> new QMUIDialog.MessageDialogBuilder(ShowAlbumPlayListActivity.this)
                .setTitle("共有" + songsList.size() + "首歌")
                .setMessage("确定要全部下载吗？")
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction(0, "确认", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
                    //仅下载当前已经刷出来的
                    List<String> ids = new ArrayList<>(songIds);//不能使用原因用，否则会出错
                    downloadBinder.startDownload(ids.subList(0, songsList.size()));
                    dialog.dismiss();
                }).show());
        album_image = findViewById(R.id.album_playlist_image);
        album_name = findViewById(R.id.album_playlist_name);
        album_play_count = findViewById(R.id.album_playlist_play_count);
        album_playlist = findViewById(R.id.album_playlist_recycler_view);
        album_creatorImg = findViewById(R.id.album_playlist_creator_image);
        album_creatorName = findViewById(R.id.album_playlist_creator_name);
        album_commentCount = findViewById(R.id.album_comment_count);
        progressBar = findViewById(R.id.progressbar);
        comment_layout = findViewById(R.id.comment_layout);
        bcgImg = findViewById(R.id.bcgImg);
        loading = findViewById(R.id.refresh_play_list);
        loading.setEnableRefresh(false);
        loading.autoLoadmore();
        loading.setOnLoadmoreListener(refreshlayout -> {
            new AlbumSongList().execute();//加载后续数据
        });
        //实现上画结束后不显示背景信息
        AppBarLayout appBar = findViewById(R.id.app_bar);
        listInfo = findViewById(R.id.list_info);
        appBar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (verticalOffset == 0) {
                listInfo.setVisibility(View.VISIBLE);
            } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                //折叠状态
                listInfo.setVisibility(View.GONE);
            }
        });
    }


    @SuppressLint("StaticFieldLeak")
    class AlbumSongList extends AsyncTask<Song, Void, List<Song>> {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        protected List<Song> doInBackground(Song... songs) {
            if (songIds.size() <= 20) {
                List<Song> list;
                list = MusicDeal.getSongListByIds(songIds);
                loading.setEnableLoadmore(false);//当数据不足20条,禁用加载
                return list;
            } else {
                List<String> list = songIds.subList(0, 20);
                songIds = songIds.subList(20, songIds.size());
                return MusicDeal.getSongListByIds(list);
            }
        }

        @Override
        protected void onPostExecute(List<Song> songs) {
            super.onPostExecute(songs);
            songsList.addAll(songs);
            listAdapter.notifyDataSetChanged();
            loading.finishLoadmore();
        }
    }
}
